<template>
  <div class="login-container">
    <!-- 左侧农产品展示区 -->
    <div class="banner-section">
      <el-carousel height="100vh" indicator-position="none" arrow="never">
        <el-carousel-item v-for="item in 3" :key="item">
          <div class="carousel-item">
            <img :src="getBgImage(item)" alt="轮播图" />
            <h2 class="slogan">连接田间与餐桌</h2>
            <p class="sub-slogan">每一口都是自然的馈赠</p>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 右侧登录表单 -->
    <div class="form-section">
      <div class="form-wrapper">
        <div class="logo">
          <img
            src="https://cdn-icons-png.flaticon.com/128/10130/10130599.png"
            alt="助农平台"
          />
        </div>

        <el-form
          :model="loginForm"
          :rules="loginRules"
          ref="loginFormRef"
          @keyup.enter="handleLogin"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入手机号/用户名"
              prefix-icon="User"
              size="large"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>

          <el-form-item prop="captcha">
            <div class="captcha-wrapper">
              <el-input
                v-model="loginForm.captcha"
                placeholder="请输入验证码"
                prefix-icon="Key"
                size="large"
              />
              <img
                :src="captchaImage"
                alt="验证码"
                class="captcha-image"
                @click="refreshCaptcha"
              />
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="login-btn"
              :loading="loading"
              @click="handleLogin"
            >
              立即登录
            </el-button>
          </el-form-item>

          <div class="form-footer">
            <el-link type="info" @click="goRegister">立即注册</el-link>
            <el-link type="info" @click="forgetPassword">忘记密码？</el-link>
          </div>
        </el-form>

        <!-- 第三方登录 -->
        <div class="social-login">
          <div class="divider">
            <span class="line"></span>
            <span class="text">其他登录方式</span>
            <span class="line"></span>
          </div>
          <div class="social-icons">
            <el-icon class="wechat-icon" @click="wechatLogin">
              <svg-icon icon-class="wechat" />
            </el-icon>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { UserControllerService } from "@/generated";
import { setToken } from "@/utils/auth";

const router = useRouter();

const loginFormRef = ref();
const loading = ref(false);
const captchaImage = ref("");

const loginForm = reactive({
  username: "",
  password: "",
  captcha: "",
});

const loginRules = reactive({
  username: [{ required: true, message: "请输入登录账号", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 18, message: "密码长度为6-18位", trigger: "blur" },
  ],
  captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});

// 直接返回外部 URL
const getBgImage = (index) => {
  return [
    "http://152.136.39.163:9000/images-dev/upload/images/d8613e7f-9832-424f-92cb-22faf1a5896c.jpg",
    "https://images.unsplash.com/photo-1597362925123-77861d3fbac7?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
    "https://images.pexels.com/photos/1482101/pexels-photo-1482101.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2",
  ][index - 1];
};

// 刷新验证码方法
const refreshCaptcha = async () => {
  // 第一步：获取验证码图片的 URL
  const res = await UserControllerService.getCaptcha();
  console.log("验证码图片的 URL:", res.data);
  if (res.code === 0) {
    // 第二步：将验证码图片的 URL 设置到 captchaImage 上
    captchaImage.value = res.data.captchaUrl;
  }
};

// 页面初始化就加载验证码
onMounted(() => {
  refreshCaptcha();
});

// 组件卸载时清理内存
onUnmounted(() => {
  if (captchaImage.value) {
    URL.revokeObjectURL(captchaImage.value);
  }
});

const handleLogin = async () => {
  console.log("handleLogin", loginForm);
  try {
    await loginFormRef.value.validate();
    loading.value = true;
    // 调用登录接口
    const res = await UserControllerService.userLogin({
      username: loginForm.username,
      password: loginForm.password,
      captcha: loginForm.captcha,
    });
    console.log("登录接口返回的数据:", res);
    if (res.code === 0) {
      // 登录成功
      // 存储 token 等信息
      setToken(res.data);
      // 跳转到首页
      await router.push("/");
      // 刷新页面
      window.location.reload();
      ElMessage.success("登录成功！");
    } else {
      // 登录失败
      ElMessage.error(res.message || "登录失败，请检查账号和密码！");
    }
    // await loginAPI(loginForm)
  } catch (error) {
    console.error("登录失败:", error);
    ElMessage.error("登录失败，请检查账号和密码！");
  } finally {
    loading.value = false;
  }
};

const goRegister = () => {
  // 跳转注册页逻辑
  router.push("/common/register");
};

const forgetPassword = () => {
  // 忘记密码逻辑
};

const wechatLogin = () => {
  // 微信登录逻辑
};
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  height: 100vh;

  .banner-section {
    flex: 1;
    background: linear-gradient(135deg, #3b873e 0%, #2c662f 100%);

    .carousel-item {
      height: 100%;
      background-size: cover;
      background-position: center;
      position: relative;

      .slogan {
        position: absolute;
        top: 20%;
        left: 10%;
        color: white;
        font-size: 36px;
        text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
      }

      .sub-slogan {
        position: absolute;
        top: calc(20% + 60px);
        left: 10%;
        color: rgba(255, 255, 255, 0.9);
        font-size: 18px;
      }
    }
  }

  .form-section {
    width: 480px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #ffffff;

    .form-wrapper {
      width: 340px;

      .logo {
        text-align: center;
        margin-bottom: 40px;

        img {
          height: 60px;
        }
      }

      .captcha-wrapper {
        display: flex;
        align-items: center;
        gap: 10px;

        .captcha-image {
          height: 40px;
          width: 160px;
          cursor: pointer;
          border: 1px solid #ddd;
          border-radius: 4px;
          transition: opacity 0.3s;

          &:hover {
            opacity: 0.8;
          }
        }
      }

      .login-btn {
        width: 100%;
        background: #3b873e;
        border-color: #3b873e;

        &:hover {
          background: #2c662f;
          border-color: #2c662f;
        }
      }

      .form-footer {
        display: flex;
        justify-content: space-between;
        margin-top: 16px;
      }

      .social-login {
        margin-top: 40px;

        .divider {
          display: flex;
          align-items: center;
          color: #999;
          margin: 20px 0;

          .line {
            flex: 1;
            height: 1px;
            background: #eee;
          }

          .text {
            padding: 0 12px;
            font-size: 12px;
          }
        }

        .social-icons {
          text-align: center;

          .wechat-icon {
            font-size: 32px;
            color: #09bb07;
            cursor: pointer;
            transition: transform 0.3s;

            &:hover {
              transform: scale(1.1);
            }
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .banner-section {
    display: none;
  }
  .form-section {
    width: 100% !important;
  }
}
</style>
